<script setup lang="ts">
import { onMounted, Ref, ref, watch, shallowRef, computed, nextTick } from 'vue'
import { Message, Modal, Notification, Spin, Divider, Image } from '@arco-design/web-vue'
import {
  IconFullscreen,
  IconFullscreenExit,
  IconClockCircle,
  IconUser,
  IconCalendar,
  IconEdit,
  IconFile,
  IconAttachment,
  IconPlus,
  IconEye,
  IconDownload,
  IconDelete,
  IconMessage,
  IconHistory,
  IconFaceSmileFill,
  IconAt,
  IconCheck,
  IconClose,
  IconCheckCircleFill
} from '@arco-design/web-vue/es/icon'
import { PRIORITY_CONFIG, getTaskPriorityColor, getPriorityLabel } from '@/constants/Priority'
import {
  BUG_STATUS_CONFIG,
  getCompleteStatus,
  getCompleteColor,
  getCompleteIcon
} from '@/constants/CompleteStatus'
import dayjs from 'dayjs'
import {
  getBugDetailUsingGet,
  pageBugDynamicsUsingPost,
  updateBugUsingPut
} from '@/api/bugController'
import { addBugCommentUsingPost, pageBugCommentUsingPost } from '@/api/bugCommentsController'
import { deleteBugCommentUsingDelete } from '@/api/bugCommentsController'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { IEditorConfig, IDomEditor } from '@wangeditor/editor'
import { editorConfig, editorStyle } from '@/composables/useEditorConfig'
import { getMembersUsingGet, getProjectUsingGet } from '@/api/projectController'
import { getMilestoneUsingGet } from '@/api/milestoneController'
import { getIterationUsingGet } from '@/api/iterationController'
import {
  addAttacheUsingPost,
  deleteAttacheUsingDelete,
  pageAttachesUsingPost
} from '@/api/attacheController'
import { uploadFileUsingPost } from '@/api/fileController'
import { getFileIcon, formatFileSize, getFileType, downloadFile, isImageFile } from '@/utils/file'
import { useFilePreview } from '@/composables/useFilePreview'
// 附件预览 （composiables 代码复用）
const { previewVisible, previewFile, handlePreview, closePreview } = useFilePreview()
//emoji
import '@/composables/emojiConfig'
import { emojiIndex, Picker } from '@/composables/emojiConfig'
import { useUserStore } from '@/store/index'
const userStore = useUserStore()

defineOptions({
  name: 'BugView'
})

// Props定义
const props = defineProps<{
  visible: boolean
  bugId: number | null
}>()

// Emits定义
const emit = defineEmits<{
  (e: 'update:visible', visible: boolean): void
  (e: 'close', bugId: number): void
}>()

//全屏控制
const fullscreen = ref(false)

// Bug数据
const bug = ref<API.BugVo>({})

// #region 编辑Bug内容
const updateBugRequest: Ref<API.UpdateBugRequest> = ref({
  id: (props.bugId as number) || undefined,
  proId: (bug.value.proId as number) || undefined,
  iterId: (bug.value.iterId as number) || undefined,
  mileId: (bug.value.mileId as number) || undefined,
  title: '',
  description: '',
  remark: '',
  status: 0,
  priority: 0,
  startTime: '',
  endTime: ''
})

// 添加标题编辑相关的状态和方法
const isEditingTitle = ref(false)
const editedTitle = ref('')

// 开始编辑标题
const startEditTitle = () => {
  editedTitle.value = bug.value?.title || ''
  isEditingTitle.value = true
}

// 保存标题
const handleTitleChange = async () => {
  if (!editedTitle.value.trim()) {
    Message.warning('标题不能为空')
    editedTitle.value = bug.value?.title || ''
    return
  }

  // 重置更新请求对象,只保留必要参数
  updateBugRequest.value = {
    id: bug.value.id,
    title: editedTitle.value,
    mileId: -1,
    iterId: -1
  }

  try {
    const res: any = await updateBugUsingPut(updateBugRequest.value)
    if (res.code === 0) {
      await getBugData()
    } else {
      Message.error(res.message)
    }
  } catch (error) {
    Message.error('更新失败')
    editedTitle.value = bug.value?.title || ''
  } finally {
    isEditingTitle.value = false
  }
}

// 修改状态
const handleStatusChange = async (status: number) => {
  // 重置更新请求对象,只保留必要参数
  updateBugRequest.value = {
    id: bug.value.id, // 保留任务ID
    status: status, // 只设置要更新的状态
    mileId: -1,
    iterId: -1
  }

  try {
    const res: any = await updateBugUsingPut(updateBugRequest.value)
    if (res.code === 0) {
      await getBugData()
    } else {
      Message.error(res.message)
    }
  } catch (error) {
    Message.error('更新失败')
  }
}

// 添加修改负责人的处理函数
const handleOwnerChange = async (userId: number) => {
  // 重置更新请求对象,只保留必要参数
  updateBugRequest.value = {
    id: bug.value.id,
    ownerId: userId,
    mileId: -1,
    iterId: -1
  }
  try {
    const res: any = await updateBugUsingPut(updateBugRequest.value)
    if (res.code === 0) {
      await getBugData()
    } else {
      Message.error(res.message)
    }
  } catch (error) {
    Message.error('更新失败')
  }
}

// 添加项目成员列表
const projectMembers = ref<API.UserVO[]>([])

// 获取项目成员
const getProjectMembers = async () => {
  if (!bug.value.proId) return
  try {
    const res: any = await getMembersUsingGet({ id: bug.value.proId })
    if (res.code === 0) {
      projectMembers.value = res.data
    } else {
      Message.error(res.message)
    }
  } catch (error) {
    console.error('获取项目成员失败:', error)
    Message.error('获取项目成员失败')
  }
}

// 添加关联任务相关的数据
const relateTask = ref<API.TaskVo>({})
const relateTaskId = ref<number | null>(null)
const useableRelateTasks = ref<API.TaskVo[]>([])

// 获取关联任务
const getRelateTask = async () => {
  if (!bug.value.taskId) return
  try {
    const res: any = await getTaskDetailUsingGet({ id: bug.value.taskId })
    if (res.code === 0) {
      relateTask.value = res.data
      relateTaskId.value = bug.value.taskId == -1 ? null : bug.value.taskId
    } else {
      Message.error(res.message)
    }
  } catch (error) {
    console.error('获取关联任务失败:', error)
    Message.error('获取关联任务失败')
  }
}

// 获取Bug相关数据
const getBugData = async () => {
  if (!props.bugId) return
  const bugId = props.bugId
  const res: any = await getBugDetailUsingGet({ id: bugId })
  if (res.code === 0) {
    bug.value = res.data
    // 添加获取动态的调用
    await Promise.all([loadMoreComment(), getProjectMembers(), loadlMoreDynamics()])
  } else {
    Message.error(res.message)
  }
}

const handleClose = () => {
  emit('update:visible', false)
  emit('close', bug.value.id as number)
}

//初始化
onMounted(async () => {
  await getBugData()
  await nextTick()
})

// 评论相关数据
const commentsList = ref<API.BugCommentVo[]>([])
const commentsLoading = ref(false)
const commentContent = ref('')
const hasMoreComment = ref(true)
const commentFiles = ref<any[]>([])
const atList = ref<API.UserVO[]>([])

// 评论分页
const commentPage = ref(1)
const commentPageSize = ref(10)

// 加载评论
const loadMoreComment = async () => {
  if (!props.bugId || commentsLoading.value || !hasMoreComment.value) return
  commentsLoading.value = true
  try {
    const res: any = await pageBugCommentUsingPost({
      current: commentPage.value,
      pageSize: commentPageSize.value,
      bugId: props.bugId
    })
    if (res.code === 0) {
      const total = res.data?.total
      // 对结果中的 params 属性解析
      const records = res.data.records.map((item: any) => {
        const processedComment = {
          ...item,
          attachments: [],
          atUsers: []
        }
        if (item.params) {
          try {
            if (item.params.A) {
              processedComment.attachments = JSON.parse(item.params.A)
            }
            if (item.params.M) {
              processedComment.atUsers = JSON.parse(item.params.M)
            }
          } catch (error) {
            console.error('解析评论参数失败:', error)
          }
        }
        return processedComment
      })

      if (commentPage.value === 1) {
        // 第一页直接赋值，使用后端返回的倒序数据
        commentsList.value = records
      } else {
        // 加载更多时，将新数据添加到列表末尾
        commentsList.value = [...commentsList.value, ...records]
      }

      // 更新页码
      commentPage.value++
      // 检查是否还有更多数据
      hasMoreComment.value = commentPage.value <= Math.ceil(total / commentPageSize.value)
    }
  } catch (error) {
    console.error('获取评论失败:', error)
    Message.error('获取评论失败')
  } finally {
    commentsLoading.value = false
  }
}

// 处理评论滚动
const handleCommentScroll = (e: any) => {
  const { scrollTop, scrollHeight, clientHeight } = e.target
  // 当滚动到距离顶部20px时加载更多
  if (scrollTop <= 20 && !commentsLoading.value && hasMoreComment.value) {
    loadMoreComment()
  }
}

// 修改处理评论附件上传函数
const handleCommentFileUpload = async (option: any) => {
  const file = option.fileItem.file
  // 验证文件大小
  if (file.size > 1024 * 1024) {
    Message.error('文件大小不能超过1M')
    return
  }

  try {
    const res: any = await uploadFileUsingPost(file)
    if (res.code === 0) {
      commentFiles.value.push({
        id: file.lastModified, // 使用 lastModified 作为唯一标识
        name: file.name,
        url: res.data
      })
    } else {
      Message.error(res.message || '文件上传失败')
    }
  } catch (error) {
    Message.error('文件上传失败' + error)
  }
}

// 移除评论附件
const removeCommentFile = (fileId: number) => {
  const index = commentFiles.value.findIndex((f) => f.id === fileId)
  if (index > -1) {
    commentFiles.value.splice(index, 1)
  }
}

// 修改发送评论的处理函数
const handleAddComment = async () => {
  if (
    !commentContent.value.trim() &&
    atList.value.length === 0 &&
    commentFiles.value.length === 0
  ) {
    Message.warning('请输入评论内容')
    return
  }

  try {
    const res: any = await addBugCommentUsingPost({
      bugId: props.bugId as number,
      content: commentContent.value,
      atUserList: atList.value.map((item) => item.id as number),
      sendId: userStore.user.id as number,
      attacheList: commentFiles.value
    })

    if (res.code === 0) {
      Message.success('评论成功')
      // 清空输入
      commentContent.value = ''
      atList.value = []
      commentFiles.value = []

      // 重新加载第一页评论
      commentPage.value = 1
      hasMoreComment.value = true
      await loadMoreComment()
    } else {
      Message.error(res.message)
    }
  } catch (error) {
    Message.error('评论失败')
  }
}

// 处理@成员
const toggleAtMember = (member: API.UserVO) => {
  const index = atList.value.findIndex((m) => m.id === member.id)
  if (index === -1) {
    // 如果不在列表中，添加成员并在评论中插入@
    atList.value.push(member)
    commentContent.value += `@${member.nickname || member.username} `
  } else {
    // 如果已在列表中，移除成员并从评论中删除@
    atList.value.splice(index, 1)
    const atText = `@${member.nickname || member.username} `
    commentContent.value = commentContent.value.replace(atText, '')
  }
}

// 处理表情选择
const showEmoji = (emoji: any) => {
  commentContent.value += emoji.native
}

// 动态相关
const dynamicsList = ref<API.BugDynamicVo[]>([])
const dynamicsLoading = ref(false)

// 加载动态
const loadlMoreDynamics = async () => {
  if (!props.bugId) return
  dynamicsLoading.value = true
  try {
    const res: any = await pageBugDynamicsUsingPost({
      current: 1,
      pageSize: 999,
      bugId: props.bugId
    })
    if (res.code === 0) {
      // 处理动态数据，确保数据结构一致
      const dynamics = res.data.records.map((item: any) => ({
        ...item,
        // 将 creator 映射为 operator 以保持一致性
        operator: item.creator || {}
      }))
      dynamicsList.value = dynamics
    } else {
      Message.error(res.message)
    }
  } catch (error) {
    console.error('获取动态失败:', error)
    Message.error('获取动态失败')
  } finally {
    dynamicsLoading.value = false
  }
}

// 添加修改优先级的处理函数
const handlePriorityChange = async (priority: number) => {
  // 重置更新请求对象,只保留必要参数
  updateBugRequest.value = {
    id: bug.value.id,
    priority: priority,
    mileId: -1,
    iterId: -1
  }

  try {
    const res: any = await updateBugUsingPut(updateBugRequest.value)
    if (res.code === 0) {
      await getBugData()
    } else {
      Message.error(res.message)
    }
  } catch (error) {
    Message.error('更新失败')
  }
}

// 添加辅助函数来获取状态的key
const getBugStatusKey = (status: number): keyof typeof BUG_STATUS_CONFIG => {
  switch (status) {
    case 0:
      return 'PENDING'
    case 1:
      return 'RESOLVED'
    case 4:
      return 'FIXED'
    case 5:
      return 'MANAGED'
    default:
      return 'PENDING'
  }
}
</script>

<template>
  <a-modal
    :visible="visible"
    @update:visible="(val) => emit('update:visible', val)"
    @cancel="handleClose"
    modal-class="bug-view-modal"
    :footer="false"
    :mask-closable="true"
    draggable
    :fullscreen="fullscreen"
    width="auto"
  >
    <!-- 标题栏部分 -->
    <template #title>
      <div class="modal-title" @dblclick="fullscreen = !fullscreen">
        <div class="title-left">
          <a-button type="secondary" size="small" class="project-info">
            <span class="project-name">{{ bug?.projectTitle }}</span>
            <span class="separator">|</span>
            <span class="bug-code">{{ bug?.code }}</span>
          </a-button>
        </div>
        <a-tooltip content="双击头部标题">
          <div class="title-actions">
            <a-button
              type="text"
              size="small"
              @click="fullscreen = !fullscreen"
              :title="fullscreen ? '退出全屏' : '全屏'"
            >
              <template #icon>
                <icon-fullscreen-exit v-if="fullscreen" />
                <icon-fullscreen v-else />
              </template>
            </a-button>
          </div>
        </a-tooltip>
      </div>
    </template>

    <template v-if="bug">
      <a-row :gutter="32" class="bug-view-content" :class="{ 'is-fullscreen': fullscreen }">
        <!-- 左侧内容区 -->
        <a-col :span="fullscreen ? 16 : 16" class="left-content">
          <div class="left-content-scroll">
            <div class="bug-header">
              <!-- 标题区域 -->
              <div
                class="title-wrapper"
                :class="{ 'is-editing': isEditingTitle }"
                @click="startEditTitle"
              >
                <a-input
                  v-if="isEditingTitle"
                  v-model="editedTitle"
                  :default-value="bug?.title"
                  @blur="handleTitleChange"
                  @keyup.enter="handleTitleChange"
                  class="title-input"
                  :max-length="100"
                  show-word-limit
                />
                <h1 v-else class="bug-main-title">
                  {{ bug.title }}
                </h1>
              </div>

              <!-- Bug基本信息行 -->
              <a-row class="bug-basic-info">
                <!-- 状态 -->
                <a-col :span="bug.status === 4 && bug.completeTime ? 4 : 6">
                  <a-popover trigger="click" position="bottom">
                    <div class="info-item">
                      <component
                        :is="
                          BUG_STATUS_CONFIG[getBugStatusKey(bug?.status)]?.icon ||
                          BUG_STATUS_CONFIG.PENDING.icon
                        "
                        class="info-icon"
                        :size="32"
                        :style="{
                          color:
                            BUG_STATUS_CONFIG[getBugStatusKey(bug?.status)]?.color ||
                            BUG_STATUS_CONFIG.PENDING.color
                        }"
                      />
                      <div class="info-content">
                        <a-tag
                          :color="
                            BUG_STATUS_CONFIG[getBugStatusKey(bug?.status)]?.color ||
                            BUG_STATUS_CONFIG.PENDING.color
                          "
                        >
                          {{
                            BUG_STATUS_CONFIG[getBugStatusKey(bug?.status)]?.label ||
                            BUG_STATUS_CONFIG.PENDING.label
                          }}
                        </a-tag>
                        <span class="info-label">状态</span>
                      </div>
                    </div>
                    <!-- 添加状态列表 -->
                    <template #content>
                      <div class="status-list">
                        <div
                          v-for="item in Object.values(BUG_STATUS_CONFIG)"
                          :key="item.value"
                          class="status-item"
                          :class="{ 'is-active': bug.status === item.value }"
                          @click="bug.status !== item.value && handleStatusChange(item.value)"
                        >
                          <component :is="item.icon" :style="{ color: item.color }" />
                          <span>{{ item.label }}</span>
                        </div>
                      </div>
                    </template>
                  </a-popover>
                </a-col>

                <!-- 优先级 -->
                <a-col :span="bug.status === 4 && bug.completeTime ? 4 : 6">
                  <a-popover trigger="click" position="bottom">
                    <div class="info-item">
                      <div
                        class="priority-icon"
                        :style="{ backgroundColor: getTaskPriorityColor(bug.priority) }"
                      >
                        P{{ bug.priority }}
                      </div>
                      <div class="info-content">
                        <a-tag :color="getTaskPriorityColor(bug.priority)">
                          {{ getPriorityLabel(bug.priority) }}
                        </a-tag>
                        <span class="info-label">优先级</span>
                      </div>
                    </div>
                    <!-- 添加优先级列表 -->
                    <template #content>
                      <div class="priority-list">
                        <div
                          v-for="item in PRIORITY_CONFIG"
                          :key="item.value"
                          class="priority-item"
                          :class="{ 'is-active': bug.priority === item.value }"
                          @click="bug.priority !== item.value && handlePriorityChange(item.value)"
                        >
                          <div class="priority-icon" :style="{ backgroundColor: item.color }">
                            P{{ item.value }}
                          </div>
                          <span>{{ item.label }}</span>
                        </div>
                      </div>
                    </template>
                  </a-popover>
                </a-col>

                <!-- 负责人 -->
                <a-col :span="bug.status === 4 && bug.completeTime ? 4 : 6">
                  <a-popover trigger="click" position="bottom">
                    <div class="info-item">
                      <a-avatar :size="32" :image-url="bug.owner?.avatar">
                        {{ bug.owner?.nickname || bug.owner?.username?.charAt(0) }}
                      </a-avatar>
                      <div class="info-content">
                        <span class="info-name">{{
                          bug.owner?.nickname || bug.owner?.username
                        }}</span>
                        <span class="info-label">负责人</span>
                      </div>
                    </div>
                    <!-- 添加成员列表 -->
                    <template #content>
                      <div class="member-list">
                        <div
                          v-for="member in projectMembers"
                          :key="member.id"
                          class="member-item"
                          :class="{ 'is-active': bug.ownerId === member.id }"
                          @click="bug.ownerId !== member.id && handleOwnerChange(member.id)"
                        >
                          <a-avatar :size="28" :image-url="member.avatar">
                            {{ member.nickname || member.username?.charAt(0) }}
                          </a-avatar>
                          <span class="member-name">{{ member.nickname || member.username }}</span>
                          <icon-check v-if="bug.ownerId === member.id" />
                        </div>
                      </div>
                    </template>
                  </a-popover>
                </a-col>

                <!-- 开始时间 -->
                <a-col :span="bug.status === 4 && bug.completeTime ? 4 : 6">
                  <div class="info-item">
                    <icon-calendar class="info-icon" :size="32" />
                    <div class="info-content">
                      <span class="time">{{
                        dayjs(bug.startTime).format('YYYY-MM-DD HH:mm:ss')
                      }}</span>
                      <span class="info-label">开始时间</span>
                    </div>
                  </div>
                </a-col>

                <!-- 截止时间 -->
                <a-col :span="bug.status === 4 && bug.completeTime ? 4 : 6">
                  <div class="info-item">
                    <icon-calendar class="info-icon" :size="32" />
                    <div class="info-content">
                      <span class="time">{{
                        dayjs(bug.endTime).format('YYYY-MM-DD HH:mm:ss')
                      }}</span>
                      <span class="info-label">截止时间</span>
                    </div>
                  </div>
                </a-col>

                <!-- 添加创建人 -->
                <a-col :span="bug.status === 4 && bug.completeTime ? 4 : 6">
                  <div class="info-item">
                    <icon-user class="info-icon" :size="32" />
                    <div class="info-content">
                      <span class="info-name">{{
                        bug.creator?.nickname || bug.creator?.username
                      }}</span>
                      <span class="info-label">创建人</span>
                    </div>
                  </div>
                </a-col>
              </a-row>

              <!-- 完成时间信息行 -->
              <a-row class="bug-complete-info" v-if="bug.status === 4 && bug.completeTime">
                <a-col :span="6">
                  <div class="info-item">
                    <icon-check-circle-fill
                      class="info-icon"
                      :size="32"
                      style="color: var(--color-success-light-4)"
                    />
                    <div class="info-content">
                      <span class="time">
                        {{ dayjs(bug.completeTime).format('YYYY-MM-DD HH:mm:ss') }}
                      </span>
                      <span class="info-label">完成时间</span>
                    </div>
                  </div>
                </a-col>
              </a-row>
            </div>

            <!-- Bug详情标签页 -->
            <a-tabs class="bug-detail-tabs">
              <a-tab-pane key="details" title="缺陷详情">
                <template #title>
                  <a-space>
                    <icon-file />
                    缺陷详情
                  </a-space>
                </template>

                <!-- Bug关联信息 -->
                <div class="bug-relations">
                  <a-row :gutter="16">
                    <!-- 关联项目 -->
                    <a-col :span="6">
                      <div class="relation-item">
                        <span class="relation-label">关联项目:</span>
                        <span class="relation-content">{{ bug.projectTitle || '无' }}</span>
                      </div>
                    </a-col>

                    <!-- 关联里程碑 -->
                    <a-col :span="6">
                      <div class="relation-item">
                        <span class="relation-label">关联里程碑:</span>
                        <span class="relation-content">{{ bug.milestoneTitle || '无' }}</span>
                      </div>
                    </a-col>

                    <!-- 关联迭代 -->
                    <a-col :span="6">
                      <div class="relation-item">
                        <span class="relation-label">关联迭代:</span>
                        <span class="relation-content">{{ bug.iterationTitle || '无' }}</span>
                      </div>
                    </a-col>

                    <!-- 关联任务 -->
                    <a-col :span="6">
                      <div class="relation-item">
                        <span class="relation-label">关联任务:</span>
                        <span class="relation-content">{{ bug.taskTitle || '无' }}</span>
                      </div>
                    </a-col>
                  </a-row>
                </div>

                <!-- Bug描述 -->
                <div class="description-wrapper">
                  <div class="section">
                    <div class="section-header">
                      <h3>描述</h3>
                    </div>
                    <div v-html="bug.description || '无'" class="content-box"></div>
                  </div>
                </div>

                <!-- Bug备注 -->
                <div class="remark-wrapper">
                  <div class="section">
                    <div class="section-header">
                      <h3>备注</h3>
                    </div>
                    <div v-html="bug.remark || '无'" class="content-box"></div>
                  </div>
                </div>
              </a-tab-pane>
            </a-tabs>
          </div>
        </a-col>

        <!-- 右侧评论区 -->
        <a-col :span="fullscreen ? 8 : 8" class="comment-col">
          <a-tabs>
            <!-- 评论面板 -->
            <a-tab-pane key="commentList" title="评论">
              <template #title>
                <a-space>
                  <icon-message />
                  评论
                </a-space>
              </template>
              <div class="comment-section">
                <!-- 评论列表区域 -->
                <div class="comment-list" @scroll="handleCommentScroll">
                  <template v-if="commentsList.length > 0">
                    <!-- 加载状态提示 -->
                    <div v-if="commentsLoading" class="comment-loading">
                      <a-spin dot />
                      <span>加载中...</span>
                    </div>
                    <!-- 没有更多数据的提示 -->
                    <div v-if="!hasMoreComment && !commentsLoading" class="no-more-comment">
                      <a-divider>没有更多评论了</a-divider>
                    </div>
                    <!-- 评论列表 -->
                    <div v-for="comment in commentsList" :key="comment.id" class="comment-item">
                      <div class="comment-layout">
                        <!-- 左侧头像区域 -->
                        <div class="comment-left">
                          <a-avatar :size="40" :image-url="comment?.sendUser?.avatar">
                            {{
                              comment?.sendUser?.nickname?.[0] || comment?.sendUser?.username?.[0]
                            }}
                          </a-avatar>
                        </div>

                        <!-- 右侧内容区域 -->
                        <div class="comment-right">
                          <!-- 发送者信息和时间 -->
                          <div class="comment-header">
                            <span class="sender-name">{{
                              comment?.sendUser?.nickname || comment?.sendUser?.username
                            }}</span>
                            <div class="header-right">
                              <span class="send-time">{{
                                dayjs(comment?.createAt).format('MM-DD HH:mm:ss')
                              }}</span>
                              <!-- 当评论是当前用户发送的才显示删除图标 -->
                              <icon-delete
                                v-if="comment.sendId === userStore.user.id"
                                class="delete-icon"
                                @click="handleDeleteComment(comment?.id)"
                              />
                            </div>
                          </div>

                          <!-- @用户列表 -->
                          <div v-if="comment.atUsers?.length" class="at-users">
                            <a-tag
                              v-for="user in comment.atUsers"
                              :key="user.id"
                              class="at-user-tag"
                            >
                              @{{ user.nickname || user.username }}
                            </a-tag>
                          </div>

                          <!-- 附件列表 -->
                          <div v-if="comment.attachments?.length" class="attachments-list">
                            <div
                              v-for="file in comment.attachments"
                              :key="file.id"
                              class="attachment-item"
                            >
                              <!-- 文件信息行 -->
                              <div class="file-info-row">
                                <icon-file class="file-icon" />
                                <span class="file-name">{{ file.name }}</span>
                                <div class="file-actions">
                                  <a-button type="text" size="mini" @click="downloadFile(file)">
                                    <icon-download />
                                  </a-button>
                                </div>
                              </div>
                              <!-- 图片预览行 -->
                              <div v-if="isImageFile(file.name)" class="image-preview-row">
                                <a-image
                                  :src="file.url"
                                  class="preview-image"
                                  fit="contain"
                                  width="100"
                                  height="100"
                                />
                              </div>
                            </div>
                          </div>

                          <!-- 评论内容 -->
                          <div class="comment-content">{{ comment.content }}</div>
                        </div>
                      </div>
                    </div>
                  </template>
                  <div v-else class="no-comments">
                    <a-divider>暂无评论</a-divider>
                  </div>
                </div>

                <!-- 评论输入区域 -->
                <div class="comment-input-wrapper">
                  <div class="comment-input">
                    <a-textarea
                      v-model="commentContent"
                      placeholder="添加评论..."
                      :auto-size="{ minRows: 2, maxRows: 5 }"
                      :max-length="2000"
                      style="width: 100%"
                      show-word-limit
                    />
                    <!-- 评论附件预览区 -->
                    <div v-if="commentFiles.length > 0" class="comment-files">
                      <div v-for="file in commentFiles" :key="file.id" class="comment-file-item">
                        <template v-if="isImageFile(file.name)">
                          <img :src="file.url" class="file-preview-image" alt="preview" />
                        </template>
                        <template v-else>
                          <icon-file class="file-icon" />
                        </template>
                        <span class="file-name">{{ file.name }}</span>
                        <icon-close class="remove-icon" @click="removeCommentFile(file.id)" />
                      </div>
                    </div>
                    <a-space class="input-actions">
                      <div class="comment-toolbar">
                        <a-space>
                          <!-- 表情按钮 -->
                          <a-popover trigger="click" position="tr">
                            <a-button class="toolbar-btn" type="text" size="small">
                              <template #icon>
                                <icon-face-smile-fill />
                              </template>
                            </a-button>
                            <template #content>
                              <Picker :data="emojiIndex" set="twitter" @select="showEmoji" />
                            </template>
                          </a-popover>

                          <!-- 艾特按钮 -->
                          <a-popover trigger="click" position="tr">
                            <a-button class="toolbar-btn" type="text" size="small">
                              <template #icon>
                                <icon-at />
                              </template>
                            </a-button>
                            <template #content>
                              <div class="member-list-container">
                                <div class="member-list-header">选择要@的成员</div>
                                <div class="member-list">
                                  <div
                                    v-for="member in projectMembers"
                                    :key="member.id"
                                    class="member-item"
                                    :class="{
                                      'is-selected': atList.some((m) => m.id === member.id)
                                    }"
                                    @click="toggleAtMember(member)"
                                  >
                                    <div class="member-info-wrapper">
                                      <a-avatar :size="24" :image-url="member.avatar">
                                        {{ member.nickname?.[0] || member.username?.[0] }}
                                      </a-avatar>
                                      <span class="member-name">{{
                                        member.nickname || member.username
                                      }}</span>
                                    </div>
                                    <icon-check v-if="atList.some((m) => m.id === member.id)" />
                                  </div>
                                </div>
                              </div>
                            </template>
                          </a-popover>

                          <!-- 附件按钮 -->
                          <div class="upload-wrapper">
                            <a-upload
                              :custom-request="handleCommentFileUpload"
                              :show-file-list="false"
                            >
                              <template #upload-button>
                                <a-button class="toolbar-btn" type="text" size="small">
                                  <template #icon>
                                    <icon-attachment />
                                  </template>
                                </a-button>
                              </template>
                            </a-upload>
                            <span class="upload-tip">大小&lt;1MB</span>
                          </div>
                        </a-space>
                      </div>
                      <a-button type="primary" size="small" @click="handleAddComment"
                        >发送</a-button
                      >
                    </a-space>
                  </div>
                </div>
              </div>
            </a-tab-pane>

            <!-- 动态面板 -->
            <a-tab-pane key="dynamics" title="动态">
              <template #title>
                <a-space>
                  <icon-history />
                  动态
                </a-space>
              </template>
              <div class="dynamics-section">
                <div class="dynamics-list">
                  <template v-if="dynamicsList?.length">
                    <div v-for="dynamic in dynamicsList" :key="dynamic.id" class="dynamic-item">
                      <div class="dynamic-header">
                        <div class="user-info">
                          <a-avatar :size="24" :image-url="dynamic.creator?.avatar">
                            {{ dynamic.creator?.nickname?.[0] || dynamic.creator?.username?.[0] }}
                          </a-avatar>
                          <span class="username">{{
                            dynamic.creator?.nickname || dynamic.creator?.username
                          }}</span>
                        </div>
                        <span class="dynamic-time">{{
                          dayjs(dynamic.createAt).format('MM-DD HH:mm:ss')
                        }}</span>
                      </div>
                      <div class="dynamic-content" v-html="dynamic.content"></div>
                    </div>
                  </template>
                  <div v-else class="no-dynamics">
                    <icon-history style="font-size: 24px; opacity: 0.3" />
                    <span>暂无动态</span>
                  </div>
                </div>
                <!-- 添加加载状态显示 -->
                <div v-if="dynamicsLoading" class="dynamic-load-wrapper">
                  <a-spin dot />
                </div>
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-col>
      </a-row>
    </template>
  </a-modal>

  <!-- 预览组件 -->
  <FilePreview v-model:isPreviewOpen="previewVisible" :file="previewFile" @close="closePreview" />
</template>

<style scoped>
/* 复制 TaskView 的完整样式 */
.bug-view-content {
  width: 1480px !important;
  min-width: 480px !important;
  max-width: 1920px !important;
  margin: 0 auto;
  height: 80vh;
  overflow: hidden;
  transition: all 0.1s ease;
}

/* 全屏状态下的样式 */
.bug-view-content.is-fullscreen {
  width: 100% !important;
  max-width: 100% !important;
  height: calc(100vh - 60px) !important; /* 减去标题栏高度 */
}

/* 修改评论区样式，添加过渡效果 */
.comment-col {
  border-left: 1px solid var(--color-border);
  height: 100%;
  transition: all 0.1s ease;
}

.comment-section {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 180px);
  position: relative;
}

/* 全屏状态下的评论区样式调整 */
.is-fullscreen .comment-section {
  height: calc(100vh - 120px);
}

.bug-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid var(--color-border);
}

/* 修改基本信息行样式 */
.bug-basic-info {
  margin-top: 16px;
  padding: 16px 0;
  border-top: 1px solid var(--color-border);
}

.bug-complete-info {
  margin-top: 16px;
  padding: 16px 0;
}

/* 修改信息项的悬浮样式 */
.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.info-item:hover {
  background-color: var(--color-fill-2);
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.info-label {
  font-size: 13px;
  color: var(--color-text-3);
}

.info-name,
.time {
  font-size: 14px;
  color: var(--color-text-1);
  line-height: 1.5;
}

.info-icon {
  font-size: 16px;
  color: var(--color-text-2);
}

/* 修改标题栏样式 */
.modal-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding-right: 40px;
}

.title-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.project-info {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 14px;
}

.project-name {
  color: var(--color-text-3);
}

.separator {
  color: var(--color-text-4);
  margin: 0 2px;
}

.bug-code {
  margin-left: 8px;
  font-size: 12px;
  font-weight: normal;
}

/* 修改左侧内容区滚动样式 */
.left-content {
  height: 100%;
  overflow: hidden;
}

.left-content-scroll {
  height: 100%;
  overflow-y: auto;
  padding-right: 16px;
  /* 隐藏滚动条但保留滚动功能 */
  -ms-overflow-style: none; /* IE and Edge */
  scrollbar-width: none; /* Firefox */
}

/* 隐藏 Webkit 浏览器的滚动条 */
.left-content-scroll::-webkit-scrollbar {
  display: none;
}

/* 修改标题相关样式 */
.title-wrapper {
  position: relative;
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  cursor: text;
  transition: all 0.1s;
}

.title-wrapper:hover {
  background-color: var(--color-fill-1);
}

.title-wrapper.is-editing {
  background-color: var(--color-bg-1);
}

.bug-main-title {
  font-size: 24px;
  font-weight: 500;
  color: var(--color-text-1);
  margin: 0;
  line-height: 1.4;
  min-height: 34px;
}

/* 修改输入框样式 */
.title-input {
  font-size: 24px !important;
  font-weight: 500 !important;
  padding: 0 !important;
}

:deep(.title-input .arco-input-wrapper) {
  padding: 0;
  background-color: transparent;
  border: none !important;
  box-shadow: none !important;
}

/* Bug关联信息样式 */
.bug-relations {
  margin: 16px 0;
  padding: 16px;
  background-color: var(--color-fill-1);
  border-radius: 4px;
}

.relation-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.relation-label {
  font-size: 13px;
  color: var(--color-text-3);
}

.relation-content {
  font-size: 14px;
  color: var(--color-text-1);
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 描述和备注区域样式 */
.section {
  margin-bottom: 12px;
}

.section h3 {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 16px;
  color: var(--color-text-1);
  border-left: 3px solid var(--color-primary);
  padding-left: 8px;
}

.content-box {
  background-color: var(--color-bg-1);
  border-radius: 4px;
  padding: 16px;
  min-height: 100px;
  font-size: 14px;
  line-height: 1.5;
  color: var(--color-text-1);
}

/* 右侧标签页样式 */
.comment-col :deep(.arco-tabs) {
  height: 100%;
}

.comment-col :deep(.arco-tabs-content) {
  height: 100%;
  overflow: hidden;
}

.comment-col :deep(.arco-tab-pane) {
  height: 100%;
  position: relative;
}

/* 响应式布局调整 */
@media screen and (max-width: 1520px) {
  .bug-view-content:not(.is-fullscreen) {
    width: 95vw !important;
  }
}

@media screen and (max-width: 1200px) {
  .bug-view-content:not(.is-fullscreen) {
    height: auto;
  }

  .comment-col {
    border-left: none;
    border-top: 1px solid var(--color-border);
    margin-top: 24px;
    padding-top: 24px;
  }
}
.comment-list {
  flex: 1;
  overflow-y: auto;
  padding-left: 8px;
  padding-bottom: 240px;
  display: flex;
  flex-direction: column; /* 恢复正常排序 */
}

/* 自定义滚动条样式 */
.comment-list::-webkit-scrollbar {
  width: 6px;
}
.comment-list::-webkit-scrollbar-thumb {
  background-color: var(--color-fill-3);
  border-radius: 3px;
}

.comment-list::-webkit-scrollbar-track {
  background-color: transparent;
}
.comment-item {
  margin-bottom: 16px;
}

.comment-layout {
  display: flex;
  gap: 12px;
}

.comment-left {
  flex-shrink: 0;
}

.comment-right {
  flex: 1;
  min-width: 0;
}

.comment-header {
  display: flex;
  align-items: center;
  justify-content: space-between; /* 修改为两端对齐 */
  margin-bottom: 5px;
}

.sender-name {
  font-size: 14px;
  font-weight: 500;
  color: var(--color-text-2);
}

.header-right {
  display: flex;
  align-items: center;
  gap: 8px;
}

.send-time {
  font-size: 12px;
  color: var(--color-text-3);
}

.delete-icon {
  font-size: 14px;
  color: var(--color-text-3);
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.2s;
}

.comment-item:hover .delete-icon {
  opacity: 1;
}

.delete-icon:hover {
  color: var(--color-danger-light-4);
}

.comment-content {
  font-size: 14px;
  line-height: 1.6;
  color: var(--color-text-1);
}

/* 评论输入区域 */
.comment-input-wrapper {
  flex: 3;
  position: absolute;
  bottom: 60px;
  left: 0;
  right: 0;
  background-color: var(--color-bg-2);
  border-top: 1px solid var(--color-border);
  padding: 16px;
  z-index: 1; /* 确保输入框在上层 */
}

.comment-input {
  width: 100%;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 8px;
}

.comment-toolbar {
  display: flex;
  gap: 8px;
}

.toolbar-btn {
  padding: 4px !important;
}

/* 成员列表样式 */
.member-list-container {
  padding: 8px;
  min-width: 200px;
  max-height: 300px;
  overflow-y: auto;
}

.member-list-header {
  padding: 4px 8px;
  color: var(--color-text-2);
  font-size: 13px;
}

.member-list {
  margin-top: 8px;
}

.member-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.2s ease;
}

.member-item.is-active {
  background-color: var(--color-fill-2);
  cursor: default;
}

.member-item:hover:not(.is-active) {
  background-color: var(--color-fill-2);
}

.member-name {
  flex: 1;
  font-size: 14px;
  color: var(--color-text-1);
  margin-right: 8px;
}

.member-item :deep(.arco-icon-check) {
  color: var(--color-primary);
  font-size: 14px;
}

/* 动态区域样式 */
.dynamics-section {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 180px);
  position: relative;
}

.dynamics-list {
  flex: 1;
  overflow-y: auto;
  padding-left: 8px;
  padding-bottom: 140px;
  display: flex;
  flex-direction: column;
}

.dynamic-item {
  margin-bottom: 16px;
  padding: 12px;
  background-color: var(--color-fill-1);
  border-radius: 4px;
}

.dynamic-load-wrapper {
  flex: 3;
  position: absolute;
  bottom: 60px;
  left: 0;
  right: 0;
  background-color: var(--color-bg-2);
  border-top: 1px solid var(--color-border);
  padding: 16px;
  z-index: 1;
  display: flex;
  justify-content: center;
  align-items: center;
}

.dynamic-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.dynamic-content {
  color: var(--color-text-2);
  font-size: 14px;
}

.no-dynamics {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 8px;
  color: var(--color-text-3);
  height: 200px;
}

/* 加载和空状态提示 */
.comment-loading,
.no-more-comment,
.no-comments {
  text-align: center;
  padding: 16px 0;
  color: var(--color-text-3);
}

/* 上传提示 */
.upload-tip {
  font-size: 12px;
  color: var(--color-text-3);
  margin-left: 4px;
}

/* 修改状态列表样式 */
.status-list {
  width: 200px;
  padding: 8px;
}

.status-item {
  padding: 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.2s ease;
  display: flex;
  align-items: center;
  gap: 8px; /* 图标和文字的间距 */
}

/* 添加选中状态的样式 */
.status-item.is-active {
  background-color: var(--color-fill-2);
  cursor: default; /* 当前选中项不显示手型光标 */
}

.status-item:hover {
  background-color: var(--color-fill-2);
}

.status-item:active {
  background-color: var(--color-fill-3);
}

/* 优先级图标样式 */
.priority-icon {
  width: 32px;
  height: 32px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #fff;
  font-weight: bold;
  font-size: 14px;
}

/* 优先级列表样式 */
.priority-list {
  width: 200px;
  padding: 8px;
}

.priority-item {
  padding: 8px;
  cursor: pointer;
  border-radius: 4px;
  transition: background-color 0.2s ease;
  display: flex;
  align-items: center;
  gap: 8px;
}

.priority-item.is-active {
  background-color: var(--color-fill-2);
  cursor: default;
}

.priority-item:hover:not(.is-active) {
  background-color: var(--color-fill-2);
}

.priority-item .priority-icon {
  width: 24px;
  height: 24px;
  font-size: 12px;
}

/* 评论附件预览区样式 */
.comment-files {
  margin-top: 8px;
  padding: 8px;
  background-color: var(--color-fill-1);
  border-radius: 4px;
}

.comment-file-item {
  display: flex;
  align-items: center;
  padding: 4px 8px;
  margin-bottom: 4px;
  border-radius: 4px;
  background-color: var(--color-bg-2);
  position: relative;
}

.comment-file-item:last-child {
  margin-bottom: 0;
}

.file-preview-image {
  width: 24px;
  height: 24px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 8px;
}

.file-icon {
  font-size: 24px;
  color: var(--color-text-3);
  margin-right: 8px;
}

.file-name {
  flex: 1;
  font-size: 13px;
  color: var(--color-text-2);
  margin-right: 24px;
  word-break: break-all;
}

.remove-icon {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  color: var(--color-text-3);
  cursor: pointer;
  transition: color 0.2s;
}

.remove-icon:hover {
  color: var(--color-text-1);
}
</style>
